<template>
  <view class="container">
    <view class="bg-sear">
      <view class="scrolltop">
        <view
          class="section"
          @tap="toSearchPage"
        >
          <image
            src="@/static/images/icon/search.png"
            class="search-img"
          />
          <text class="placeholder">
            搜索
          </text>
        </view>
      </view>
    </view>

    <view class="content">
      <!-- swiper -->
      <swiper
        :autoplay="autoplay"
        :indicator-color="indicatorColor"
        :interval="interval"
        :duration="duration"
        :indicator-active-color="indicatorActiveColor + ' '"
        :circular="true"
        class="pic-swiper"
        indicator-dots
        previous-margin="20rpx"
        next-margin="20rpx"
      >
        <block
          v-for="(item, index) in indexImgs"
          :key="index"
        >
          <swiper-item class="banner-item">
            <view class="img-box">
              <image
                :src="item.imgUrl"
                :data-prodid="item.relation"
                class="banner"
                @tap="toProdPage"
              />
            </view>
          </swiper-item>
        </block>
      </swiper>
      <!-- end swiper -->

      <view class="cat-item">
        <view
          class="item"
          data-sts="1"
          @tap="toClassifyPage"
        >
          <image src="@/static/images/icon/newProd.png" />
          <text>新品推荐</text>
        </view>
        <view
          class="item"
          data-sts="2"
          @tap="toClassifyPage"
        >
          <image src="@/static/images/icon/timePrice.png" />
          <text>热度排行</text>
        </view>
        <view
          class="item"
          data-sts="3"
          @tap="toClassifyPage"
        >
          <image src="@/static/images/icon/neweveryday.png" />
          <text>每日疯抢</text>
        </view>
        <view
          class="item"
          @tap="toCommunityPage"
        >
          <image src="@/static/images/icon/community.png" />
          <text>宠物社区</text>
        </view>
      </view>

      <!-- 消息播放 -->
      <view
        v-if="news && news.length"
        class="message-play"
        @tap="onNewsPage"
      >
        <image
          src="@/static/images/icon/horn.png"
          class="hornpng"
        />
        <swiper
          :vertical="true"
          :autoplay="true"
          :circular="true"
          duration="1000"
          class="swiper-cont"
        >
          <block
            v-for="(item, index) in news"
            :key="index"
          >
            <swiper-item class="items">
              {{ item.title }}
            </swiper-item>
          </block>
        </swiper>
        <text class="arrow" />
      </view>
    </view>

    <view v-if="updata" class="updata">
      <!-- 每日上新、更多宝贝 -->
      <template v-if="items && items.length">
        <block v-for="(item, index) in items" :key="index">
          <!-- 每日上新 -->
          <view
            v-if="item.style==='2' && item.prods && item.prods.length"
            class="up-to-date"
          >
            <view class="title">
              <text>{{ item.title }}</text>
              <view
                class="more-prod-cont"
                data-sts="0"
                :data-id="item.id"
                :data-title="item.title"
                @tap="toClassifyPage"
              >
                <text class="more">
                  查看更多
                </text>
              </view>
            </view>
            <view class="item-cont">
              <div v-if="item?.prods?.length">
                <block
                  v-for="(prod, index2) in item.prods"
                  :key="index2"
                >
                  <view
                    class="prod-item"
                    :data-prodid="prod.prodId"
                    @tap="toProdPage"
                  >
                    <view>
                      <view class="imagecont">
                        <!-- <img-show
                          :src="prod.pic"
                          :class-list="['prodimg']"
                        /> -->
                        <img :src="prod.pic" class="prodimg">
                      </view>
                      <view class="prod-text">
                        {{ prod.prodName }}
                      </view>
                      <view class="price">
                        <text class="symbol">
                          ￥
                        </text>
                        <text class="big-num">
                          {{ wxs.parsePrice(prod.price)[0] }}
                        </text>
                        <text class="small-num">
                          .{{ wxs.parsePrice(prod.price)[1] }}
                        </text>
                      </view>
                    </view>
                  </view>
                </block>
              </div>
            </view>
          </view>
          <!-- 更多宝贝 -->
          <view
            v-if="item.style==='0' && item.prods && item.prods.length"
            class="more-prod"
          >
            <view class="title">
              {{ item.title }}
            </view>
            <view class="prod-show">
              <div v-if="item?.prods?.length">
                <block
                  v-for="(prod, index2) in item.prods"
                  :key="index2"
                >
                  <view
                    class="show-item"
                    :data-prodid="prod.prodId"
                    @tap="toProdPage"
                  >
                    <view class="more-prod-pic">
                      <img-show
                        :src="prod.pic"
                        :class-list="['more-pic']"
                      />
                    </view>
                    <view class="prod-text-right">
                      <view class="prod-text more">
                        {{ prod.prodName }}
                      </view>
                      <view class="prod-info">
                        {{ prod.brief }}
                      </view>
                      <view class="b-cart">
                        <view class="price">
                          <text class="symbol">
                            ￥
                          </text>
                          <text class="big-num">
                            {{ wxs.parsePrice(prod.price)[0] }}
                          </text>
                          <text class="small-num">
                            .{{ wxs.parsePrice(prod.price)[1] }}
                          </text>
                        </view>
                        <image
                          src="@/static/images/tabbar/basket-sel.png"
                          class="basket-img"
                          @tap.stop="addToCart(prod)"
                        />
                      </view>
                    </view>
                  </view>
                </block>
              </div>
            </view>
          </view>
        </block>
      </template>
      <!-- 商城热卖（热度排行） -->
      <view v-if="hotList && hotList.length" class="hot-sale">
        <view class="title">
          <text>热度排行</text>
        </view>
        <view class="hotsale-item-cont">
          <div v-if="hotList?.length">
            <block v-for="(prod, index) in hotList" :key="index">
              <view class="prod-items" :data-prodid="prod.prodId" @tap="toProdPage">
                <view class="hot-imagecont">
                  <img-show :src="prod.pic" :class-list="['hotsaleimg']" />
                </view>
                <view class="hot-text">
                  <view class="hotprod-text">{{ prod.prodName }}</view>
                  <view class="prod-info">{{ prod.brief }}</view>
                  <view class="prod-text-info">
                    <view class="price">
                      <text class="symbol">￥</text>
                      <text class="big-num">{{ wxs.parsePrice(prod.price)[0] }}</text>
                      <text class="small-num">.{{ wxs.parsePrice(prod.price)[1] }}</text>
                    </view>
                    <image src="@/static/images/tabbar/basket-sel.png" class="basket-img" />
                  </view>
                </view>
              </view>
            </block>
          </div>
        </view>
      </view> 
    </view>

    <!-- 猜你喜欢区域，放在 taglist 循环外面，只渲染一次 -->
    <view class="guess-like">
      <view class="title">
        猜你喜欢
      </view>
      <scroll-view class="guess-prod-list-horizontal" scroll-x>
        <view class="guess-grid">
          <block v-for="(prod, index) in guessYouLike" :key="index">
            <view class="guess-card" :data-prodid="prod.prodId" @tap="toProdPage">
              <view class="guess-img-box">
                <img-show :src="prod.pic" :class-list="['guess-pic-large']" />
              </view>
              <view class="guess-info">
                <view class="guess-title">{{ prod.prodName }}</view>
                <view class="guess-brief">{{ prod.brief }}</view>
                <view class="guess-meta">
                  <text v-if="prod.shopName" class="shop-name">{{ prod.shopName }}</text>
                  <text v-if="prod.sales" class="sales">销量: {{ prod.sales }}</text>
                </view>
                <view class="guess-price-row">
                  <text class="guess-price">￥{{ wxs.parsePrice(prod.price)[0] }}.<span class="small">{{ wxs.parsePrice(prod.price)[1] }}</span></text>
                  <text v-if="prod.originalPrice && prod.originalPrice > prod.price" class="guess-original">￥{{ prod.originalPrice }}</text>
                  <text v-if="prod.discount" class="guess-discount">{{ prod.discount }}折</text>
                </view>
                <view class="guess-btn-row">
                  <button class="guess-btn guess-fav" @tap.stop="() => onFav(prod)">收藏</button>
                  <button class="guess-btn guess-cart" @tap.stop="() => addToCart(prod)">加入购物车</button>
                </view>
              </view>
            </view>
          </block>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import number from '@/wxs/number.js'  // 确保这行在最上面
const wxs = number()  // 正确初始化 wxs
const indicatorColor = ref('#d1e5fb')
const indicatorActiveColor = ref('#1b7dec')
const autoplay = ref(true)
const interval = ref(2000)
const duration = ref(1000)
const indexImgs = ref([])
const seq = ref(0)
const news = ref([])
const taglist = ref([])
const updata = ref(true)
const guessYouLike = ref([])
const hotList = ref([])

// 确保所有数组类型的数据都被正确初始化
const data = reactive({
  tagList: [], // 初始化为空数组而不是 undefined
  prods: [],   // 初始化为空数组而不是 undefined
  items: []    // 初始化为空数组而不是 undefined
})

onLoad(() => {
  // 打印本地存储的 token 和 loginResult
  console.log('onLoad: accessToken:', uni.getStorageSync('accessToken'))
  console.log('onLoad: loginResult:', uni.getStorageSync('loginResult'))
  getAllData()
})
onShow(() => {
  // #ifdef MP-WEIXIN
  uni.getSetting({
    success (res) {
      if (!res.authSetting['scope.userInfo']) {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      }
    }
  })
  // #endif
  http.getCartCount() // 重新计算购物车总数量
})

onPullDownRefresh(() => {
  // 模拟加载
  setTimeout(() => {
    getAllData()
    uni.stopPullDownRefresh() // 停止下拉刷新
  }, 100)
})

const getAllData = () => {
  // 打印 token 信息
  console.log('getAllData: accessToken:', uni.getStorageSync('accessToken'))
  console.log('getAllData: loginResult:', uni.getStorageSync('loginResult'))
  http.getCartCount()
  getIndexImgs()
  getNoticeList()
  getTag()
  getGuessYouLike()
  getHotList()
}

const toProdPage = (e) => {
  const prodid = e.currentTarget.dataset.prodid

  if (prodid) {
    uni.navigateTo({
      url: '/pages/prod/prod?prodid=' + prodid
    })
  }
}
/**
 * 加入购物车
 * @param item
 */
const addToCart = (item) => {
  uni.showLoading({
    mask: true
  })
  http.request({
    url: '/prod/prodInfo',
    method: 'GET',
    data: {
      prodId: item.prodId
    }
  })
    .then(({ data }) => {
      http.request({
        url: '/p/shopCart/changeItem',
        method: 'POST',
        data: {
          basketId: 0,
          count: 1,
          prodId: data.prodId,
          shopId: data.shopId,
          skuId: data.skuList[0].skuId
        }
      })
        .then(() => {
          uni.hideLoading()
          http.getCartCount() // 重新计算购物车总数量
          uni.showToast({
            title: '加入购物车成功',
            icon: 'none'
          })
        })
    })
}


/**
 * 跳转搜索页
 */
const toSearchPage = () => {
  uni.navigateTo({
    url: '/pages/search-page/search-page'
  })
}

/**
 * 跳转商品活动页面
 * @param e
 */
const toClassifyPage = (e) => {
  let url = '/pages/prod-classify/prod-classify?sts=' + e.currentTarget.dataset.sts
  const id = e.currentTarget.dataset.id
  const title = e.currentTarget.dataset.title

  if (id) {
    url += '&tagid=' + id + '&title=' + title
  }

  uni.navigateTo({
    url
  })
}
/**
 * 跳转公告列表页面
 */
const onNewsPage = () => {
  uni.navigateTo({
    url: '/pages/recent-news/recent-news'
  })
}

/**
 * 加载轮播图
 */
const getIndexImgs = () => {
  http.request({
    url: '/indexImgs',
    method: 'GET',
    data: {}
  })
    .then(({ data }) => {
      indexImgs.value = data
      seq.value = data
    })
}

const getNoticeList = () => {
  // 加载公告
  http.request({
    url: '/shop/notice/topNoticeList',
    method: 'GET',
    data: {}
  })
    .then(({ data }) => {
      news.value = data
    })
}

/**
 * 加载商品标题分组列表
 */
const getTag = () => {
  http.request({
    url: '/prod/tag/prodTagList',
    method: 'GET',
    data: {}
  })
    .then(({ data }) => {
      // 初始化每个 item 的 prods 为 []
      taglist.value = data.map(item => ({ ...item, prods: [] }))
      for (let i = 0; i < data.length; i++) {
        updata.value = false
        updata.value = true
        getTagProd(data[i].id, i)
      }
    })
}

const getTagProd = (id, index) => {
  http.request({
    url: '/prod/prodListByTagId',
    method: 'GET',
    data: {
      tagId: id,
      size: 6
    }
  })
    .then(({ data }) => {
      updata.value = false
      updata.value = true
      const taglistParam = taglist.value
      if (!Array.isArray(data.records)) {
        console.error('data.records 不是数组', data.records)
      }
      taglistParam[index].prods = Array.isArray(data.records) ? data.records : []
      taglist.value = taglistParam
    })
}

const toCommunityPage = () => {
  uni.navigateTo({
    url: '/pages/community/community'
  })
}

const getGuessYouLike = async () => {
  // 优先从 userInfo 获取 userId
  const userInfo = uni.getStorageSync('userInfo')
  const loginResult = uni.getStorageSync('loginResult')
  const token = loginResult?.accessToken || uni.getStorageSync('accessToken')
  const userId = userInfo?.userId

  console.log('猜你喜欢参数:', {
    userId,
    token,
    loginResult,
    userInfo
  })

  if (!token || !userId) {
    console.log('用户未登录，无法获取推荐')
    guessYouLike.value = []
    return
  }

  try {
    // 添加详细的请求日志
    console.log('开始请求推荐接口:', `/p/recommend/user/${userId}`)
    
    const response = await http.request({
      url: `/p/recommend/user/${userId}`,
      method: 'GET',
      header: {
        'Authorization': token
      }
    })
    
    console.log('推荐接口完整响应:', response)
    
    // 检查响应结构
    if (response.data && Array.isArray(response.data)) {
      guessYouLike.value = response.data
      console.log('成功设置推荐商品列表，数量:', guessYouLike.value.length)
    } else if (response.data && response.data.data && Array.isArray(response.data.data)) {
      // 处理可能的包装响应结构
      guessYouLike.value = response.data.data
      console.log('成功设置推荐商品列表（内层data），数量:', guessYouLike.value.length)
    } else {
      console.error('推荐接口返回格式异常:', response)
      guessYouLike.value = []
    }
    
  } catch (err) {
    console.error('获取推荐商品失败:', {
      error: err,
      message: err.message,
      status: err.statusCode
    })
    
    // 如果是 401 未授权，可能需要重新登录
    if (err.statusCode === 401) {
      console.log('token 已过期，需要重新登录')
      // 可以触发重新登录流程
      uni.navigateTo({
        url: '/pages/accountLogin/accountLogin'
      })
    }
    
    guessYouLike.value = []
  }
}

const getHotList = () => {
  http.request({
    url: '/prod/moreCollectionProdList',
    method: 'GET',
    data: {
      size: 6 // 你可以根据需要调整数量
    }
  }).then(({ data }) => {
    // data.records 是商品数组
    hotList.value = data.records || []
  })
}

const onFav = (prod) => {
  uni.showToast({ title: '已收藏', icon: 'success' })
}
</script>

<style scoped lang="scss">
@use './index.scss';

// 猜你喜欢宫格横滑样式
.guess-prod-list-horizontal {
  width: 100%;
  overflow-x: scroll;
  white-space: nowrap;
  padding-bottom: 20rpx;
}
.guess-grid {
  display: flex;
  flex-direction: row;
  gap: 24rpx;
}
.guess-card {
  width: 320rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.08);
  margin-bottom: 10rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 16rpx 16rpx 16rpx;
  transition: box-shadow 0.2s;
}
.guess-card:active {
  box-shadow: 0 8rpx 24rpx rgba(27,125,236,0.15);
}
.guess-img-box {
  width: 260rpx;
  height: 260rpx;
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 12rpx;
}
.guess-pic-large {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.guess-info {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.guess-title {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 6rpx;
  color: #222;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.guess-brief {
  font-size: 24rpx;
  color: #888;
  margin-bottom: 6rpx;
  height: 32rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.guess-meta {
  font-size: 22rpx;
  color: #999;
  margin-bottom: 6rpx;
  display: flex;
  gap: 12rpx;
}
.shop-name {
  color: #1b7dec;
}
.sales {
  color: #fa6400;
}
.guess-price-row {
  display: flex;
  align-items: baseline;
  gap: 10rpx;
  margin-bottom: 8rpx;
}
.guess-price {
  font-size: 32rpx;
  color: #fa6400;
  font-weight: bold;
}
.guess-price .small {
  font-size: 22rpx;
}
.guess-original {
  font-size: 22rpx;
  color: #bbb;
  text-decoration: line-through;
}
.guess-discount {
  font-size: 22rpx;
  color: #ff4d4f;
  background: #fff0f0;
  border-radius: 8rpx;
  padding: 0 8rpx;
}
.guess-btn-row {
  display: flex;
  gap: 12rpx;
  margin-top: 8rpx;
}
.guess-btn {
  font-size: 24rpx;
  padding: 0 18rpx;
  height: 48rpx;
  line-height: 48rpx;
  border-radius: 24rpx;
  border: none;
  background: #f5f7fa;
  color: #1b7dec;
}
.guess-fav {
  background: #fff7e6;
  color: #fa6400;
}
.guess-cart {
  background: #e6f7ff;
  color: #1b7dec;
}
</style>
